package sample;

import com.sun.deploy.net.HttpResponse;
import javafx.scene.image.ImageView;
import sun.net.www.http.HttpClient;
import uk.gov.gchq.gaffer.bitmap.serialisation.json.BitmapJsonModules;

import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.image.Image;

import javax.swing.*;

public class Httpmethod {

    String requestAddress=null;
    /**
     * GET方式获取厂商tab列表
     * @return  返回字符串
     * @throws Exception
     */
    public static String getFactorys() throws Exception{
        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        String hostAddress = address.getHostAddress();//192.168.0.121
        String Url="http://"+hostAddress+":8080/getFactorys";
       // String Url="http://192.168.31.100/getFactorys";
        System.out.println("getFactorys被调用了");
        URL url = new URL(Url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(8000);
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        InputStream is = conn.getInputStream();
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        String result = null;
        result = sbf.toString();

        return result;
        /*if (conn.getResponseCode() == 200) {//用于获得返回数据才能发送数据，不然数据一直在缓存数据中
            InputStream inputStream = conn.getInputStream();
            byte[] data = StreamTool.read(inputStream);
            return new String(data);
        }
        return null;*/
    }

    /**
     * 以GET方式发送厂商名。得到主题列表
     * @param params 要发送的数组
     * @param encoding  发送的编码
     * @return  true返回成功，false返回失败
     * @throws Exception
     */
    public static String  getThemeByFactory(HashMap<String,String> params, String encoding) throws Exception{
        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        String hostAddress = address.getHostAddress();//192.168.0.121
        String Url="http://"+hostAddress+":8080/getThemeByFactory";
        StringBuilder url = new StringBuilder(Url);
        url.append("?");
        for (Map.Entry<String,String> entry: params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));
            url.append("&");
        }
        url.deleteCharAt(url.length()-1);
        HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        String result = null;
        result = sbf.toString();

        return result;

    }

    /*根据主题名获取预览图*/
    public static ImageView  getPreviewByTheme(HashMap<String,String> params, String encoding) throws Exception{
        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        String hostAddress = address.getHostAddress();//192.168.0.121
        String Url="http://"+hostAddress+":8080/getPreviewByTheme";
        StringBuilder url = new StringBuilder(Url);
        url.append("?");
        for (Map.Entry<String,String> entry: params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));
            url.append("&");
        }
        url.deleteCharAt(url.length()-1);
        HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int length = 0;

        // 这里是输出到目录下
        String name=params.get("themeName");
        String previewPath="C:"+ File.separator+"preview"+File.separator+params.get("themeName");
        File file=new File(previewPath);
        if(!file.exists()){
            file.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(previewPath+File.separator+name+".png");

        // 将输入流循环写到关联文件的输出流
        while ((length = is.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, length);
        }
        File testFile=new File(previewPath+File.separator+name+".png");
        Image image=new Image(testFile.toURI().toURL().toString());
        ImageView imageView = new ImageView(image);
        return imageView;
    }

    /*下载主题压缩包*/
    public static boolean  getFileByTheme(HashMap<String,String> params, String encoding) throws Exception{
        String themeName=params.get("themeName");
        System.out.println("下载中...");
        String path= Paths.get("C:","myItz",themeName,themeName+".itz").toString();
        System.err.println("path>>"+path);
        InputStream inputStream = null;

        RandomAccessFile randomAccessFile = null;
        try {
            InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
            String hostAddress = address.getHostAddress();//192.168.0.121
            String Url="http://"+hostAddress+":8080/downloadByThemeName";
            StringBuilder url = new StringBuilder(Url);
            url.append("?");
            for (Map.Entry<String,String> entry: params.entrySet()) {
                url.append(entry.getKey()).append("=");
                url.append(URLEncoder.encode(entry.getValue(), encoding));
                url.append("&");
            }
            url.deleteCharAt(url.length()-1);

            HttpURLConnection urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Accept-Encoding", "identity");
            urlConnection.setRequestProperty("User-Agent", " Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
            urlConnection.setConnectTimeout(10 * 1000);
            File file = new File(path);
            if (!file.exists())
                file.mkdirs();
            if (file.exists())
                file.delete();
            file.createNewFile();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = urlConnection.getInputStream();
                int len = 0;
                byte[] data = new byte[4096];
                long  progres = 0; //用于保存当前进度（具体进度）
                long maxProgres = urlConnection.getContentLength();//获取文件
                randomAccessFile = new RandomAccessFile(file, "rw");
                System.err.println(maxProgres);

                ProgressBarThread pbt = new ProgressBarThread("正在下载...");
                // 调用进度条
                pbt.setVisible();
                Thread thread = new Thread(pbt);
                thread.start();

                randomAccessFile.setLength(maxProgres);//设置文件大小
                double unit = maxProgres / 100;//将文件大小分成100分，每一分的大小为unit
                double unitProgress = 0; //用于保存当前进度(1~100%)
                while (-1 != (len = inputStream.read(data))) {
                    randomAccessFile.write(data, 0, len);
                    progres += len;//保存当前具体进度
                    double temp = progres / unit; //计算当前百分比进度
                    if (temp >= 1 && temp > unitProgress) {//如果下载过程出现百分比变化
                        unitProgress = temp;//保存当前百分比
                        pbt.updateProgressBar((int)unitProgress);//写完一次，更新进度条
                      //  System.out.println("正在下载中..." + unitProgress + "%");
                    }
                }
                inputStream.close();
                System.out.println("下载完成...");
            } else {
                System.out.println("服务器异常...");
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != randomAccessFile) {
                randomAccessFile.close();
            }
        }


       /* StringBuilder url = new StringBuilder("http://192.168.31.100:8080/downloadByThemeName");
        url.append("?");
        for (Map.Entry<String,String> entry: params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));
            url.append("&");
        }
        url.deleteCharAt(url.length()-1);
        HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();

        byte[] buffer = new byte[1024];
        int length = 0;

        // 这里是输出到目录下
        String name=params.get("themeName");
        String previewPath="C:"+ File.separator+"myItz"+File.separator+params.get("themeName");
        File file=new File(previewPath);
        if(!file.exists()){
            file.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(previewPath+File.separator+name+".itz");

        // 将输入流循环写到关联文件的输出流
        while ((length = is.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, length);
        }*/

      return true;
    }

    /*根据主题名获取主题详细信息*/
    public static String  getThemeByName(HashMap<String,String> params, String encoding) throws Exception{
        StringBuilder url = new StringBuilder("http://192.168.31.100:8080/getThemeByName");
        url.append("?");
        for (Map.Entry<String,String> entry: params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));
            url.append("&");
        }
        url.deleteCharAt(url.length()-1);
        HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        String result = null;
        result = sbf.toString();

        return result;

    }



}
